package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.Result.PageResult;
import com.itheima.reggie.common.Result.Result;
import com.itheima.reggie.dto.EmployeeDTO;
import com.itheima.reggie.dto.EmployeePageQueryDTO;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@RestController
@Slf4j
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录接口，若登录成功将员工id存入Session
     *
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public Result<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        //1.将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //2.根据页面提交的用户名username查询数据库
        String username = employee.getUsername();
        LambdaQueryWrapper<Employee> employeeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        employeeLambdaQueryWrapper.eq(username != null, Employee::getUsername, username);
        Employee emp = employeeService.getOne(employeeLambdaQueryWrapper);
        //3.如果没有查询到则返回用户不存在
        if (emp == null) {
            return Result.error("用户不存在");
        }
        //4.密码比对，如果不一致则返回密码不正确
        if (!emp.getPassword().equals(password)) {
            return Result.error("密码不正确");
        }
        //5.查询员工状态，如果为禁用状态，就返回员工已禁用
        if (emp.getStatus() == 0) {
            return Result.error("员工已禁用");
        }
        //6.登录成功，将员工id存入Session并返回登陆成功结果
        request.getSession().setAttribute("employee", emp.getId());
        log.info("id为{}的员工登录成功",emp.getId());
        return Result.success(emp, "登录成功");
    }

    /**
     * 登出
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request) {
        Long empId = (Long) request.getSession().getAttribute("employee");

        if (empId != null) {
            log.info("id为{}的员工登出，清除session中保存的id信息", empId);
        }
        request.getSession().removeAttribute("employee");
        return Result.success("退出成功");
    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     * @return
     */
    @PostMapping
    public Result saveEmployee(@RequestBody EmployeeDTO employeeDTO/*, HttpServletRequest request*/) {
//        Long userId = (Long) request.getSession().getAttribute("employee");
        employeeService.saveEmployee(employeeDTO);
        return Result.success();
    }

    /**
     * 分页查询员工
     *
     * @param employeePageQueryDTO
     * @return
     */
    @GetMapping("/page")
    public Result<PageResult> listEmployee(EmployeePageQueryDTO employeePageQueryDTO) {
        log.info("分页查询，参数如下:page = {} ,pageSize = {},name = {}", employeePageQueryDTO.getPage(),
                employeePageQueryDTO.getPageSize(), employeePageQueryDTO.getName());
        PageResult pageResult = employeeService.listEmployee(employeePageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 修改员工状态
     * @param employee
     * @return
     */
    @PutMapping
    public Result<String> updateEmployee (/*HttpServletRequest request ,*/@RequestBody Employee employee){
//        Long userId = (Long) request.getSession().getAttribute("employee");
        Long id = employee.getId();
        if (id == 1){
            return Result.error("无法禁用管理员");
        }
        String password = employee.getPassword();
        if (password == null || password.isEmpty() ){
            password = "123456";
        }
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        employee.setPassword(password);
//        employee.setUpdateUser(userId);
//        employee.setUpdateTime(LocalDateTime.now());
        employeeService.updateById(employee);
        return Result.success();
    }

    /**
     * 根据员工id回显数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<Employee> getEmployeeById(@PathVariable Long id){
        log.info("员工回显数据查询，id是：{}",id);

        return Result.success(employeeService.getById(id));
    }
}
